# coding = utf-8
import datetime
import logging
import os
import time
import base64
from io import BytesIO

from PIL import Image
from django.core.cache import cache
from django.db.models import Sum, Q
from django.db.models.query import EmptyQuerySet
from django.forms import model_to_dict
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView

from member.api.utils import get_retailer_by_openid, get_retailer, get_employee_by_openid
from member.models import Retailer, RetailerImage, Employee, BonusPoint, PointConsumption, WxPermission, WxRole
from users.api.serializers import UserInfoReadOnlySerializer
from wine import settings

from rest_framework import status, filters

from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from django.db import transaction
from wxchat.api.permissions import WeixinPermission
from wxchat.api.serializers import WxUserInfoSerializer, UserRoleSerializer
from wxchat.api.template_message import send_message_to_retailer, send_message_to_client, \
    send_consumption_message_to_client
from wxchat.api.utils import get_openid_from_header, get_user_by_openid
from wxchat.models import WxUserInfo

from .serializers import RetailerSerializer, RetailerImageSerializer, EmployeeSerializer, BonusPointSerializer, \
    PointConsumptionSerializer, WxPermissionSerializer, WxRoleSerializer

logger = logging.getLogger("django")

# class RetailerListAPIView(ListAPIView):
#     """商家列表"""
#     permission_classes = ()
#     serializer_class = RetailerListSerializer
#     queryset = Retailer.objects.all()
#     pagination_class = None


class WxRetailerViewSet(ModelViewSet):
    """商家"""
    authentication_classes = ()
    permission_classes = (WeixinPermission, )
    queryset = Retailer.objects.all()
    serializer_class = RetailerSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        openid = serializer.validated_data["openid"]
        user_info = WxUserInfo.objects.filter(openid=openid).first()
        if user_info:
            serializer.validated_data["boss_name"] = user_info.name or user_info.nickname
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)


class WxRetailerImageViewSet(ModelViewSet):
    """商家图片"""
    authentication_classes = ()
    # permission_classes = (WeixinPermission, )
    permission_classes = ()
    pagination_class = None
    queryset = RetailerImage.objects.all()
    serializer_class = RetailerImageSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        retailer_id = self.request.query_params.get("retailer_id")

        if retailer_id:
            queryset = queryset.filter(retailer_id=retailer_id)

        return queryset


class WxRetailerImageUploadAPIView(APIView):
    authentication_classes = ()
    # permission_classes = (WeixinPermission,)

    def post(self, request, *args, **kwargs):
        # 接收文件
        file = request.FILES.get('image', None)
        retailer_id = request.data.get("retailer_id", None)

        print(file, retailer_id)
        if file and retailer_id:
            upload_path = RetailerImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'retailer_id': retailer_id,
                'name': file.name,
                'image': file_url,
            }

            obj = RetailerImage.objects.create(**data)
            dict_obj = {
                "id":   obj.id,
                "name": obj.name,
                "retailer_id": obj.retailer_id,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class WxRetailerInfo(APIView):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None

    def get(self, request):
        openid = get_openid_from_header(request)
        msg = {
            "status_code": "",
            "message": "",
            "retailer": {},
        }
        if openid:
            retailer = get_retailer_by_openid(openid)
            if retailer:
                retailer_info = {
                    "id": retailer.id,
                    "name": retailer.name,
                    "address": retailer.address,
                    "flag": retailer.flag,
                    "telephone": retailer.telephone,
                }

                msg["status_code"] = status.HTTP_200_OK
                msg["message"] = "数据请求成功"
                msg["retailer"] = retailer_info
                return Response(msg)

        msg["status_code"] = status.HTTP_401_UNAUTHORIZED
        msg["message"] = "数据请求失败"
        return Response(msg)


class WxBonusPointAPIView(APIView):
    """积分赠与"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def post(self, request):
        msg = {
            "status_code": "",
            "message": "",
            "data": {},
        }
        key = request.data.get("key", None)
        if key:
            url = cache.get(key)
            openid = get_openid_from_header(request)  # 客户OPENID
            user = get_user_by_openid(openid)
            if url is None:
                if user:
                    msg["data"] = model_to_dict(user)
                msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                msg["message"] = "二维码失效,请重新扫码"
                return Response(msg)
            else:
                retailer_openid = request.data.get("pid", None)
                retailer_openid = base64.b64decode(retailer_openid)
                retailer_openid = retailer_openid.decode()

                retailer_id = request.data.get("retailer_id", None)
                retailer_id = int(retailer_id)

                money = request.data.get("money", None)
                try:
                    money = int(money)
                    if money < 0:
                        raise ValueError
                except ValueError:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "数据异常！！"
                    return Response(msg)

                ok = BonusPoint.objects.filter(order_key=key).exists()
                if ok:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "积分已经赠送完毕,无须再次操作"
                    return Response(msg)

                with transaction.atomic():
                    save_id = transaction.savepoint()
                    try:
                        # 商家减积分
                        retailer = Retailer.objects.get(id=retailer_id)

                        if retailer.score is None:
                            retailer.score = 0

                        if retailer.score >= money:
                            unused_score = 0
                            used_score = money
                        else:
                            if retailer.score > 0:
                                unused_score = money - retailer.score
                                used_score = retailer.score
                            else:
                                used_score = 0
                                unused_score = money

                        retailer.score -= money
                        retailer.save(update_fields=["score"])

                        employee_user = Employee.objects.filter(openid=retailer_openid).first()
                        name = ""
                        branch = ""
                        if employee_user:
                            name = employee_user.name
                            branch = employee_user.branch
                        else:
                            retailer_user = Retailer.objects.get(openid=retailer_openid)
                            if retailer_user:
                                name = retailer_user.person
                            else:
                                wx_user = WxUserInfo.objects.get(openid=retailer_openid)
                                name = wx_user.name or wx_user.nickname

                        # 客户增加积分
                        user = WxUserInfo.objects.get(openid=openid)

                        if user.score is None:
                            user.score = 0
                        if user.unused_score is None:
                            user.unused_score = 0

                        user.score += used_score
                        user.unused_score += unused_score

                        user.save(update_fields=["score", "unused_score", "card_num"])
                        # 创建赠送积分记录
                        data = {
                            "retailer_id": int(retailer_id),
                            "openid": retailer_openid,
                            "name": name,
                            "branch": branch,
                            "customer_openid": openid,
                            "customer_name": user.name or user.nickname,
                            "score": used_score,
                            "unused_score": unused_score,
                            "total_score": retailer.score,
                            "customer_total_score": user.score,
                            "order_key": key,
                            "status": 1     # 赠送
                        }
                        obj = BonusPoint.objects.create(**data)
                        msg["status_code"] = status.HTTP_200_OK
                        msg["message"] = "成功领取积分"
                        msg["data"] = model_to_dict(user)
                        msg["points"] = money
                        # 发送模板消息
                        if obj:
                            # 商家
                            send_message_to_retailer(obj)
                            # 客户
                            send_message_to_client(obj)
                    except Exception as ex:
                        print(ex)
                        transaction.savepoint_rollback(save_id)
                        if user:
                            msg["data"] = model_to_dict(user)
                        msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                        msg["message"] = "赠送积分失败, 请联系管理员"
                        return Response(msg)

                    transaction.savepoint_commit(save_id)
                    cache.delete(key)
        else:
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "参数错误"

        return Response(msg)


class WxBonusPointCancelAPIView(APIView):
    """积分取消"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def post(self, request):
        msg = {
            "status_code": "",
            "message": "",
            "data": {},
        }

        retailer_id = request.data.get("retailer_id", None)
        retailer_id = int(retailer_id)
        bp_id = request.data.get("bp_id", None)

        if bp_id:
            point = BonusPoint.objects.filter(id=int(bp_id), retailer_id=retailer_id, status=1).first()
            if point:
                try:
                    retailer = point.retailer
                    customer_openid = point.customer_openid
                    customer = get_user_by_openid(customer_openid)
                    if retailer and customer:
                        with transaction.atomic():
                            save_id = transaction.savepoint()
                            try:
                                # 商家积分增加
                                if retailer.score is None:
                                    retailer.score = 0

                                retailer.score += point.score + point.unused_score
                                retailer.save(update_fields=["score"])
                                # 客户积分减少
                                customer.score -= point.score
                                if customer.score < 0:
                                    customer.score = 0
                                customer.unused_score -= point.unused_score
                                if customer.unused_score < 0:
                                    customer.unused_score = 0
                                customer.save(update_fields=["score", "unused_score"])

                                data = {
                                    "retailer_id": point.retailer_id,
                                    "openid": point.openid,
                                    "name": point.name,
                                    "branch": point.branch,
                                    "customer_openid": point.customer_openid,
                                    "customer_name": point.customer_name,
                                    "score": -point.score,
                                    "unused_score": -point.unused_score,
                                    "total_score": retailer.score,
                                    "customer_total_score": customer.score,
                                    "order_key": point.order_key,
                                    "status": 0  # 赠送
                                }
                                obj = BonusPoint.objects.create(**data)

                                point.status = 0
                                point.save(update_fields=["status"])

                                msg["status_code"] = status.HTTP_200_OK
                                msg["message"] = "取消积分成功!"
                                serializer = BonusPointSerializer(instance=obj)
                                msg["data"] = serializer.data
                                print(customer.score, customer.unused_score)
                            except Exception as ex:
                                print(ex)
                                transaction.savepoint_rollback(save_id)
                                msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                                msg["message"] = "取消积分失败!"
                                return Response(msg)

                            transaction.savepoint_commit(save_id)
                except Exception as e:
                    logging.error("Exception:{}".format(e))
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "取消积分失败!!"
                    return Response(msg)
        else:
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "参数异常!!"
            return Response(msg)

        return Response(msg)


class WxEmployeeAuthAPIView(APIView):
    """员工授权"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def post(self, request):
        msg = {
            "status_code": "",
            "message": "",
            "data": {},
        }
        key = request.data.get("key", None)
        openid = get_openid_from_header(request)  # 员工OPENID
        user = get_user_by_openid(openid)

        retailer = get_retailer(openid)
        if retailer:
            if user:
                msg["data"] = model_to_dict(user)
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "商家账户不能再被授权"
            return Response(msg)

        employee = get_employee_by_openid(openid)
        if employee:
            if user:
                msg["data"] = model_to_dict(user)
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "已经授权,不能再被授权".format(employee.retailer.name)
            return Response(msg)

        if key:
            url = cache.get(key)
            if url is None:
                if user:
                    msg["data"] = model_to_dict(user)
                msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                msg["message"] = "二维码失效,请重新扫码"
                return Response(msg)
            else:
                retailer_openid = request.data.get("pid", None)
                retailer_openid = base64.b64decode(retailer_openid)
                retailer_openid = retailer_openid.decode()

                retailer_id = request.data.get("retailer_id", None)
                retailer_id = int(retailer_id)

                begin_date = request.data.get("begin_date", None)
                end_date = request.data.get("end_date", None)

                name = request.data.get("name", None)
                telephone = request.data.get("telephone", None)
                branch = request.data.get("branch", None)
                role = request.data.get("role", None)

                print(begin_date, end_date, retailer_id, openid, retailer_openid, key, name, telephone, branch, role)
                ok = Employee.objects.filter(auth_key=key, confirm=1).exists()
                if ok:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "此授权码已经使用,无法再次使用"
                    return Response(msg)

                ok1 = Employee.objects.filter(openid=openid, confirm=1).exists()
                if ok1:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "此用户已经授权，无法再次授权"
                    return Response(msg)

                retailer_user = get_user_by_openid(retailer_openid)
                if user and retailer_user:
                    data = {
                        "retailer_id": int(retailer_id),
                        "openid": openid,
                        "name": name or user.name,
                        "telephone": telephone,
                        "branch": branch,
                        "begin_date": begin_date,
                        "end_date": end_date,
                        "confirm": 1,
                        "role_id": role,
                        "auth_key": key
                    }
                    employee = Employee.objects.create(**data)
                    # 更新对应的微信数据
                    user.name = name
                    user.telephone = telephone
                    user.save(update_fields=["name", "telephone"])

                    serializer = EmployeeSerializer(instance=employee)
                    employee = serializer.data
                    # employee.pop("id")
                    employee.pop("auth_key")
                    employee.pop("openid")
                    employee.pop("retailer")
                    msg["status_code"] = status.HTTP_200_OK
                    msg["message"] = "授权成功"
                    msg["data"] = model_to_dict(user)
                    msg["employee"] = employee
                    cache.delete(key)
                else:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "用户不存在, 请确认是否关注公众号"
                    return Response(msg)
        else:
            if user:
                msg["data"] = model_to_dict(user)
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "参数错误"

        return Response(msg)


class WxBonusPointViewSet(ModelViewSet):
    """赠送积分"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    queryset = BonusPoint.objects.all()
    serializer_class = BonusPointSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        openid = self.request.query_params.get("openid", None)
        employee_openid = self.request.query_params.get("employee_openid", None)
        retailer_id = self.request.query_params.get("retailer_id", None)
        name = self.request.query_params.get("name", None)
        begin_date = self.request.query_params.get("begin_date", None)
        end_date = self.request.query_params.get("end_date", None)

        if openid:
            queryset = queryset.filter(customer_openid=openid)

        if employee_openid:
            queryset = queryset.filter(openid=employee_openid)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(name__contains=name)

        if begin_date and end_date:
            queryset = queryset.filter(update_time__date__range=[begin_date, end_date])

        queryset = queryset.filter(order_key__isnull=False)

        return queryset


class WxConsumePointAPIView(APIView):
    """积分消费"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def post(self, request):
        msg = {
            "status_code": "",
            "message": "",
            "data": {},
        }
        key = request.data.get("key", None)
        client_openid = get_openid_from_header(request)  # 客户OPENID
        user = get_user_by_openid(client_openid)
        if key:
            url = cache.get(key)
            if url is None:
                msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                msg["message"] = "二维码失效,请重新扫码"
                if user:
                    msg["data"] = model_to_dict(user)
                return Response(msg)
            else:
                retailer_openid = request.data.get("openid", None)
                retailer_openid = base64.b64decode(retailer_openid).decode()

                point = request.data.get("point", None)
                try:
                    point = int(point)
                    if point < 0:
                        raise ValueError
                except ValueError:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "数据异常！！"
                    return Response(msg)

                # 判断积分是否充足
                score = user.score or 0
                if score < point:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "积分不足！！"
                    return Response(msg)

                ok = PointConsumption.objects.filter(consume_key=key).exists()
                if ok:
                    if user:
                        msg["data"] = model_to_dict(user)
                    msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                    msg["message"] = "本次积分已经消费完毕,无须再次操作"
                    return Response(msg)

                with transaction.atomic():
                    save_id = transaction.savepoint()
                    try:
                        # 客户扣除积分
                        user = WxUserInfo.objects.get(openid=client_openid)
                        user.score -= point
                        user.save(update_fields=["score", "card_num"])

                        retailer_user = WxUserInfo.objects.get(openid=retailer_openid)

                        # 创建客户消费积分记录
                        data = {
                            "openid": client_openid,
                            "name": user.name or user.nickname,
                            "employee_openid": retailer_openid,
                            "employee_name": retailer_user.name or retailer_user.nickname,
                            "score": point,
                            "total_score": user.score,
                            "consume_key": key
                        }
                        obj = PointConsumption.objects.create(**data)
                        msg["status_code"] = status.HTTP_200_OK
                        msg["message"] = "客户积分消费成功"
                        msg["data"] = model_to_dict(user)
                        msg["point"] = point
                        # 发送模板消息
                        if obj:
                            send_consumption_message_to_client(obj)

                    except Exception as ex:
                        print(ex)
                        transaction.savepoint_rollback(save_id)
                        if user:
                            msg["data"] = model_to_dict(user)
                        msg["status_code"] = status.HTTP_401_UNAUTHORIZED
                        msg["message"] = "客户积分消费失败, 请联系管理员"
                        return Response(msg)

                    transaction.savepoint_commit(save_id)
                    cache.delete(key)
        else:
            msg["status_code"] = status.HTTP_401_UNAUTHORIZED
            msg["message"] = "参数错误"
            if user:
                msg["data"] = model_to_dict(user)

        return Response(msg)


class WxPointConsumptionViewSet(ReadOnlyModelViewSet):
    """消费积分"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    queryset = PointConsumption.objects.all()
    serializer_class = PointConsumptionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        openid = self.request.query_params.get("openid", None)

        if openid:
            queryset = queryset.filter(openid=openid)

        queryset = queryset.filter(consume_key__isnull=False)

        return queryset


class WxContactImageUploadAPIView(APIView):
    authentication_classes = ()
    # permission_classes = (WeixinPermission,)

    def post(self, request, *args, **kwargs):
        # 接收文件
        file = request.data.get('image', None)
        retailer_id = request.data.get("retailer_id", None)

        # print(file, retailer_id)
        if file and retailer_id:
            upload_path = RetailerImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            imgdata = base64.b64decode(file)
            f = BytesIO(imgdata)
            image = Image.open(f)
            image_url = '{0}.png'.format(int(time.time()))
            image_path = os.path.join(dirs, image_url)
            image.save(image_path, quality=100)

            data = {
                'name': image_url,
                'image': os.path.join(upload_path, image_url),
            }

            obj, created = RetailerImage.objects.update_or_create(retailer_id=retailer_id, defaults=data)
            dict_obj = {
                "id":   obj.id,
                "name": obj.name,
                "retailer_id": obj.retailer_id,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class WxEmployeeViewSet(ModelViewSet):
    """授权员工"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        if self.lookup_field in self.kwargs:
            return queryset

        return queryset


class WxBonusStatsAPIView(APIView):
    """商家积分统计"""
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def get(self, request, *args, **kwargs):
        retailer_id = request.query_params.get("retailer_id", None)
        name = request.query_params.get("name", None)
        begin_date = request.query_params.get("begin_date", None)
        end_date = request.query_params.get("end_date", None)

        queryset = BonusPoint.objects.all()

        if retailer_id:
            queryset = queryset.filter(retailer_id=retailer_id)

        if begin_date and end_date:
            queryset = queryset.filter(update_time__date__range=[begin_date, end_date])

        if name:
            queryset = queryset.filter(name__contains=name)

        queryset = queryset.filter(order_key__isnull=False)

        results = queryset.aggregate(scores=Sum('score'), unused_scores=Sum('unused_score'))

        return Response(results)


class WxPermissionViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission, )
    pagination_class = None
    queryset = WxPermission.objects.filter(flag=1)
    serializer_class = WxPermissionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        if self.lookup_field in self.kwargs:
            return queryset

        return queryset


class WxRoleViewSet(ModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = WxRole.objects.all()
    serializer_class = WxRoleSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        openid = get_openid_from_header(self.request)
        user = get_user_by_openid(openid)

        if user and user.staff == 1:
            return queryset

        return self.serializer_class.Meta.model.objects.none()


class WxRolePermissionViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = WxPermission.objects.filter(flag=0)
    serializer_class = WxPermissionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        openid = get_openid_from_header(self.request)
        retailer = get_retailer(openid)

        if retailer:
            return queryset

        # employee = get_employee_by_openid(openid)
        # if employee:
        #     perms = employee.role.permissions.values("id")
        #     print(perms)
        #     queryset = queryset.filter(id__in=perms)
        #     return queryset

        return WxPermission.objects.none()


class WxAdminPermissionViewSet(ReadOnlyModelViewSet):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = WxPermission.objects.all()
    serializer_class = WxPermissionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        openid = get_openid_from_header(self.request)
        wx_user = get_user_by_openid(openid)

        if wx_user:
            if wx_user.staff == 1:
                return queryset.filter(Q(flag=1) | Q(flag=2))
            elif wx_user.staff == 2:
                employee = get_employee_by_openid(openid)
                if employee:
                    perms = employee.role.permissions.all()
                    queryset = queryset.filter(id__in=perms)
                    return queryset

        return WxPermission.objects.none()


class WxUserInfoAPIView(APIView):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)

    def get(self, request, *args, **kwargs):
        openid = get_openid_from_header(self.request)
        if openid:
            user = get_user_by_openid(openid)

            serializer = WxUserInfoSerializer(user, context={"request": request})
            return Response(serializer.data)

        return Response({})


class WxUserInfoListView(ListAPIView):
    authentication_classes = ()
    permission_classes = (WeixinPermission,)
    pagination_class = None
    queryset = WxUserInfo.objects.filter(staff=2)
    serializer_class = UserRoleSerializer

